﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Dancer_Partner_Matching
{
    public class Dancer
    {
        /*                       
         * [舞者] 这里指定为 [男性]
         * [舞伴] 这里指定为 [女性]
         * 
         * 两者可以互换,
         * 比如 当舞者为[男性] 则舞伴为 [女性] 同理可以反推.   
         */

        public Dancer(string name)
        {
            this.Name = name;
            this._candidateIndex = 0;
            this.Prefs = new List<Dancer>();
        }

        /// <summary>
        /// 当前候选的舞伴索引
        /// </summary>
        private int _candidateIndex;

        public string Name { get; set; }
        /// <summary>
        /// 候选的舞伴列表(根据先后顺序排名)
        /// </summary>
        public List<Dancer> Prefs { get; set; }
        public Dancer Partner { get; set; }

        /// <summary>
        /// 是否更喜欢新舞伴胜过现在的舞伴
        /// </summary>
        /// <param name="newPartner"></param>
        /// <returns></returns>
        public bool IsPrefers(Dancer newPartner)
        {
            if (this.Partner == null)
                return true;

            var prefsNew = this.Prefs.FindIndex(o => o == newPartner);
            var prefsNow = this.Prefs.FindIndex(o => o == this.Partner);

            return prefsNew < prefsNow;
        }

        /// <summary>
        /// 从候选偏好列表中选择排名最高的自由舞伴
        /// </summary>
        /// <returns></returns>
        public Dancer GetPartnerInPrefs()
        {
            if (this._candidateIndex >= this.Prefs.Count)
                return null;

            return this.Prefs[this._candidateIndex++];
        }

        /// <summary>
        /// 给舞者设置新的舞伴
        /// </summary>
        /// <param name="newPartner"></param>
        public void SetPartner(Dancer newPartner)
        {
            //如果新舞伴的之前已有舞伴,则将新舞伴之前的舞伴设置为自由状态(无舞伴)
            if (newPartner.Partner != null)
                newPartner.Partner.Partner = null;

            newPartner.Partner = this; //同时将新舞伴的舞伴设置当前舞者

            //如果当前舞者之前已有舞伴,则将当前舞者的舞伴设置为自由状态(无舞伴)
            if (this.Partner != null)
                this.Partner.Partner = null;

            this.Partner = newPartner;
        }

        public override string ToString()
        {
            return string.Format("{0} :P> {1}", this.Name, string.Join(",", this.Prefs.Select(p => p.Name)));
        }
    }
}
